const express = require('express');
const  React =  require('react');
const ReactDom = require('react-dom/server');
const { renderToString }  = ReactDom;
const { serve,  build,transformSync } = require("esbuild");
const path  = require('path');
const app = express();
app.use(express.static(__dirname + '/public'));

app.get('*',function(req,res){
    build({
		// entryPoints: [path.resolve(__dirname,"../src/App.jsx")],
		entryPoints: ["App.jsx"],
		outfile: './dist/app.js',
		minify: false,
		bundle: false,
        write: false,
        format: 'cjs',
        absWorkingDir: '/Users/junyitan/Desktop/study/ssrTemp/my-ssr/client/src/'
	}).then(source => {
		// console.log("esbuild result:",source)
        // 获取转换后的文本
        const {text} = source.outputFiles[0];
        // 文本转runtime 执行
        const Main = eval(text).default
        // 生成React元素
        const MainDom = React.createElement(Main, null);
        // react元素转换成dom字符串
        const content = renderToString(MainDom );
        const html = `
                <html>
                    <head>
                        <title>MY SSR</title>
                        <link rel="stylesheet" href="App.css">
                        <style>*{margin:0;padding:0}</style>
                    </head>
                    <body>
                        <div id="root">${content}</div>
                        <script>
                            window.__SSR_DATAS = {name: 'Caroline', age: 18}
                        </script>
                        <script type="module" crossorigin src="http://127.0.0.1:8080/assets/index.6434210b.js"></script>
                        <link rel="modulepreload" href="http://127.0.0.1:8080/assets/vendor.e16bd027.js">
                    </body>
                </html>
            `
        res.send(html)
	})
})

app.listen(4000,()=>{
	console.log("服务在4000端口启动")
})